var fs = require('fs');
var path = require('path');
var RLines = require('./renderLines');
var OUTPUT_FILE_NAME = "cad.json";
var res_struct = []
var THREE = require('three')
fs.readFile('struct.json',function(err,data){
    if(err){
        return console.error(err);
    }
    var dxf = data.toString();//将二进制的数据转换为字符串
    dxf = JSON.parse(dxf);//将字符串转换为json对象
    //entity['LWPOLYLINE'] = renderEntity(entity['LWPOLYLINE'])
    dxf.entities.map(function(e,i){
        if(e.layer.indexOf('DN') >= 0){
            switch(e.type){
                case 'LWPOLYLINE':
                case 'LINE':
                case 'POLYLINE':   
                    if(e.layer == 'DN400' || e.layer == 'DN300' ||e.layer == 'DN250' ||e.layer == 'DN200'){
                        var len = 0
                        for(var index = 0;index < e.vertices.length - 1;index ++){
                            len += Math.sqrt(Math.pow(e.vertices[index].x - e.vertices[index + 1].x, 2) + Math.pow(e.vertices[index].y - e.vertices[index +  1].y, 2))
                        }
                        e.userData = {id:i,chr:[],layer:e.layer,len:len,dn:parseInt(e.layer.replace('DN',''))}
                        res_struct.push(e)
                    }
                    break;
            }
        }  
    })
    rlines = new RLines(0.1,res_struct)
    rlines.action()
    
    rlines.lines = rlines.lines.map(function(e){
        var chr = []
        rlines.lines.map(function(l){
            if(e.userData.chr.indexOf(l.userData.id) >= 0){
                chr.push({dn:l.userData.dn,id:l.userData.id})
            }
        })
        e.userData.chr = chr
        return e
    })
    dxf.entities = rlines.lines
    var struct = {
        id:532,
        dn:400,
        len:0,
        slen:0,
        chr:{},
        list:{},
        area:[]
    }
    render(struct,rlines.lines)
    var lines = []
    struct.area.map(function(e){
        if(!e.b){
           struct.area.map(function(m){
               for(var i = 0;i < e.area.length ;i ++){
                if(m.chr.indexOf(e.area[i]) >= 0){
                    m.area = m.area.concat(e.area)
                    return 
                }
               }
               
           })
           //console.log("dd",e.len)
        }
    })
   
    var num = 0
    struct.area.map(function(e,i){
        if(e.b){
            rlines.lines.map(function(line){
                //console.log(e.indexOf(line.userData.id),line.userData.id)
                if(e.area.indexOf(line.userData.id + '') >= 0){
                    line.layer = 'DMA' + num
                    line.userData.layer = line.layer
                    lines.push(line)
                }
            })
            dxf.tables.layer.layers['DMA' + num] = {color:255,name:'DMA' + num}
            num ++
        }
    })

    dxf.entities = dxf.entities.concat(lines)

    var stc = {
        points:[],
        indices:[],
        colors:[]
    }
    dxf.entities.map(function(p){
        var material = new THREE.LineBasicMaterial({linewidth: 1, color: p.color});
        if(p.shape){
            p.vertices.push(p.vertices[0])
        }
        p.vertices.map(function(e,i){
            if (i == 0 || i == p.vertices.length - 1) {
                stc.indices.push(stc.points.length / 3)
            }
            else {
                stc.indices.push(stc.points.length  / 3, stc.points.length / 3)
            }
            stc.points.push(e.x, e.y, e.z)
            stc.colors.push(material.color.r, material.color.g, material.color.b);
        })
    })
    console.log(stc.points.length,stc.indices.length,stc.colors.length)
    fs.writeFileSync(OUTPUT_FILE_NAME, JSON.stringify(stc));
    //console.log(res)
})

function render(s,l){
    l.map(function(e,i){
        if(e.userData.id == s.id){
            s.len += e.userData.len
            s.slen += e.userData.len * 100 /e.userData.dn

            s.chr[s.id] = {b:true,dn:s.dn}
            s.list[s.id] = {b:true,dn:s.dn}

            e.userData.chr.map(function(n){
                if(!s.list[n.id] || s.list[n.id].b == false){
                    if(!s.chr[n.id]){
                        s.chr[n.id] = {b:false,dn:n.dn}
                    }
                }
            })
        }
    })
    
    if(s.slen < 2000){
        var maxid,maxdn = 0
        for(var key in s.chr){
            if(s.chr[key].b == false){
                if(s.chr[key].dn > maxdn){
                    maxid = key
                    maxdn = s.chr[key].dn
                }
            }
        }
        if(maxid){
            s.id = maxid
            s.dn = maxdn
            return render(s,l)
        }
    }
    //console.log(s)
    var area = [],chr = []
    for(var key in s.chr){
        if(s.chr[key].b == true){
            area.push(key)
        }
        else{
            if(!s.list[key]){
                s.list[key] = s.chr[key]
                chr.push(key)
            }
        }
    }
    s.len = 0
    
    console.log(s.slen)
    
    s.chr = {}

    if(s.slen > 500){
        s.area.push({area:area,len:s.slen,b:true,chr:chr})
    }
    else{
        s.area.push({area:area,len:s.slen,b:false,chr:chr})
    }
    
    s.slen = 0
    for(var key in s.list){
        if(s.list[key].b == false){
            s.id = key
            s.dn = s.list[key].dn
            return render(s,l)
        }
    }
}

/*
管径类比，管径系数
最小分区长度
最大分区长度
管网材质
管网管龄


cad.json

struct = {
    'layer0':[
        {
            type:'line',
            flag:true,
            points:[],
            indices[],
            colors:[]
        }
    ]
}
*/
